package com.gitee.magic.jdbc.persistence.source;

import java.lang.reflect.InvocationTargetException;

import com.gitee.magic.context.PropertyConverterEditor;
import com.gitee.magic.jdbc.persistence.EntityFactory;
import com.gitee.magic.jdbc.persistence.EntityFactoryAware;
import com.gitee.magic.jdbc.persistence.EntityObject;
import com.gitee.magic.jdbc.persistence.EntityProperty;
import com.gitee.magic.jdbc.persistence.RepositoryException;

/**
 * @author start
 */
public class AbstractEntityManager implements EntityFactory,EntityFactoryAware {

	private EntityFactory entityFactory;

	@Override
	public void setEntityFactory(EntityFactory factory) {
		this.entityFactory=factory;
	}
	
	@Override
	public void registerEntityDefinition(EntityObject entity) {
		this.entityFactory.registerEntityDefinition(entity);
	}

	@Override
	public EntityObject getEntityDefinition(Class<?> prototype) {
		return entityFactory.getEntityDefinition(prototype);
	}

	@Override
	public Boolean isOrmEntity(Class<?> prototype) {
		return entityFactory.isOrmEntity(prototype);
	}
	
	protected void setEntityValue(Object instance,Class<?> prototype,Object value,EntityProperty member){
		Object conversionValue = PropertyConverterEditor.in(prototype,member.getFieldName(),member.getDataType(), value);
		try {
			member.getDescriptor().getWriteMethod().invoke(instance, conversionValue);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new RepositoryException(e);
		}
	}
	
	/**
	 * 获取已经设置的主键值
	 * @param prototype
	 * @param eObject
	 * @param entity
	 * @return
	 */
	protected Object getPrimaryKeyValue(Class<?> prototype,EntityObject eObject,Object entity) {
		Object primaryKeyValue=null;
		try {
			primaryKeyValue = eObject.getEntityPropertyStubPrimaryKey().getDescriptor().getReadMethod().invoke(entity);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new RepositoryException(e);
		}
		// 主键不能为空
		if (primaryKeyValue == null) {
			throw new RepositoryException(eObject.getName()+"实体的主键值为空！");
		}
		return PropertyConverterEditor.out(prototype,eObject.getEntityPropertyStubPrimaryKey().getFieldName(),eObject.getEntityPropertyStubPrimaryKey().getDataType(),primaryKeyValue);
	}
	
}
